package com.joker.registration.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.joker.registration.hosp.repository.HospitalRepository;
import com.joker.registration.hosp.service.HospitalService;
import model.com.manubao.yygh.model.hosp.Hospital;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

/**
* @author 20405
* @description 针对表【hospital_set(医院设置表)】的数据库操作Service实现
* @createDate 2022-03-16 14:41:19
*/
@Service
public class HospitalServiceImpl implements HospitalService {
    @Autowired
    private HospitalRepository hospitalRepository;

    @Override
    public String save(Map<String, Object> paramMap) {
        //把参数map集合转换对象 Hospital医院对象
        //log.info(JSONObject.toJSONString(paramMap));
        String mapString = JSONObject.toJSONString(paramMap);
        Hospital hospital = JSONObject.parseObject(mapString, Hospital.class);

        //1.判断是否存在数据(根据编号查询)
        String hoscode = hospital.getHoscode();
        Hospital targetHospital = hospitalRepository.getHospitalByHoscode(hoscode);
        //在HospitalRepository中创建getHospitalByHoscode()方法（见下）

        //2.如果存在，进行修改
        if(null != targetHospital) {
            hospital.setStatus(targetHospital.getStatus());
            hospital.setCreateTime(targetHospital.getCreateTime());
            hospital.setUpdateTime(new Date());
            hospital.setIsDeleted(0);
            //调用repository中的save()方法修改
            hospitalRepository.save(hospital);
            //如果继承了MongoRepository接口，Spring Data自动处理，使用save方法时，当主键在集合中存在时，会进行更新， 数据整体都会更新 ，新数据会替换掉原数据 ID 以外的所有数据。ID 不存在则新增一条数据
            return "用户已存在，数据修改";
        } else { //3.如果不存在，进行添加
            hospital.setStatus(0); //0：未上线    1：已上线
            hospital.setCreateTime(new Date()); //获系统时间
            hospital.setUpdateTime(new Date()); //获系统时间
            hospital.setIsDeleted(0);
            //调用repository中的save()方法保存
            hospitalRepository.save(hospital);
            return "用户添加成功";
        }

    }
}




